package com.hmall.search.util;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.ArrayList;
import java.util.Map;

public class ResponseUtil {
    public static PageDTO<ItemDoc> respHandler(SearchResponse response){
        SearchHit[] hits = response.getHits().getHits();
        ArrayList<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField field = highlightFields.get("name");
            if (field != null){
                String highText = field.getFragments()[0].string();
                itemDoc.setName(highText);
            }
            list.add(itemDoc);
        }
        long value = response.getHits().getTotalHits().value;
        return new PageDTO<ItemDoc>(value,list);
    }
}
